package com.globaldom.web.sales;

import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.globaldom.model.CivResource;
import com.globaldom.model.MilResource;
import com.globaldom.model.Sales;
import com.globaldom.utils.Constants;
import com.globaldom.utils.EMF;
import com.globaldom.utils.MemCacheManager;
import com.globaldom.utils.Notifications;
import com.globaldom.utils.SessionManager;

@Controller
@RequestMapping(value = "/buysales")
public class SalesBuyController {
	public SalesBuyController() {
	}
	private static final Logger log = Logger.getLogger(SalesBuyController.class.getName());

	@RequestMapping(value = "/buy", method = RequestMethod.GET)
	public @ResponseBody
	Map<String, String> addCivilian(@RequestParam String saleid, HttpSession session, HttpServletRequest request) {
		Map<String, String> map = new HashMap<String, String>();
		String personID = SessionManager.getID(request, session);
		if (null == personID) {
			map = new HashMap<String, String>();
			map.put(Constants.STATUS, "-ER");
			map.put(Constants.CODE, "401");
			return map;
		}
		int saleType;
		long saleNum;
		long salePrice;
		EntityManager em = EMF.get().createEntityManager();
		EntityManager emx = EMF.get().createEntityManager();
		EntityManager emsale = EMF.get().createEntityManager();
		EntityManager emdollar = EMF.get().createEntityManager();
		try {

			Sales sale = emsale.find(Sales.class, new Long(saleid));
			if (null == sale)
				throw new RuntimeException("This Item was purchased by someone else!");
			saleType = sale.getSaleType();
			saleNum = sale.getSaleAmount();
			salePrice = sale.getSalePrice();

			CivResource cvdollar = null;
			if (saleType < 6) {
				// set military resource here
				String sql = "select c from MilResource c where person=:pid AND ResType=:restype";
				Query query = em.createQuery(sql);
				query.setParameter("pid", personID);
				query.setParameter("restype", saleType);
				MilResource mil = (MilResource) query.getSingleResult();

				long avail = mil.getMilAvailable() + saleNum;
				mil.setMilAvailable(avail);
				em.persist(mil);
				MemCacheManager.removeFreeResources(personID);

			} else if (saleType < 12) {
				CivResource cv = null;

				String sql = "select c from CivResource c where person=:pid AND ResType=:restype";
				Query query = em.createQuery(sql);
				query.setParameter("pid", personID);
				query.setParameter("restype", (saleType - 6));
				cv = (CivResource) query.getSingleResult();
				long avail = cv.getResAvailable() + saleNum;
				cv.setResAvailable(avail);
				em.persist(cv);
			}

			String sql = "select c from CivResource c where person=:pid AND ResType=:restype";
			Query query = emdollar.createQuery(sql);
			query.setParameter("pid", personID);
			query.setParameter("restype", CivResource.DOLLAR);
			cvdollar = (CivResource) query.getSingleResult();

			CivResource sellerDollar = null;
			sql = "select c from CivResource c where person=:pid AND ResType=:restype";
			query = emx.createQuery(sql);
			query.setParameter("pid", sale.getPerson());
			query.setParameter("restype", CivResource.DOLLAR);
			sellerDollar = (CivResource) query.getSingleResult();

			cvdollar.setResAvailable(cvdollar.getResAvailable() - salePrice);
			sellerDollar.setResAvailable(sellerDollar.getResAvailable() + salePrice);
			emsale.remove(sale);
			emx.persist(sellerDollar);
			emdollar.persist(cvdollar);
			MemCacheManager.removeCivics(personID);
			MemCacheManager.removeCivics(sale.getPerson());
			Notifications notice = new Notifications(sale.getPerson(), " Your item for sale has been sold/", "");
			MemCacheManager.addNotification(sale.getPerson(), notice);

			map.put(Constants.STATUS, "+OK");
			map.put(Constants.CODE, "200");
			map.put("saleprice", "" + salePrice);
			map.put("saletype", "" + saleType);
			map.put("saleamount", "" + saleNum);
		} catch (RuntimeException rte) {
			map.put(Constants.STATUS, "+-ER");
			map.put(Constants.CODE, "EDE");

		} catch (Exception ex) {
			log.severe("Error during transaction" + ex);
			map.put(Constants.STATUS, "+-ER");
			map.put(Constants.CODE, ex.getLocalizedMessage());
		} finally {
			MemCacheManager.removeMySales(personID);
			em.close();
			emsale.close();
			emx.close();
			emdollar.close();

		}

		return map;
	}

}
